package zhongbo.java.air.websocet;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName PusWebsocket
 * @Description 客户端
 * @Author 红
 * @Date 2025/4/7 10:12
 */
@ServerEndpoint(value = "/websocket/live")
@Component
@Slf4j
public class PusWebsocket {
    private static final Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void open(Session session) {
        String sessionId = session.getId();
        System.out.println("建立连接：id：" + sessionId);
        sessionMap.put(sessionId, session);

    }

    @OnClose
    public void close(Session session, CloseReason reason) {
        String closeId = session.getId();
        String reasonPhrase = reason.getReasonPhrase();
        System.out.println("关闭ws连接: {}, reason: {}" + closeId + reasonPhrase);
        sessionMap.remove(closeId, session);
    }

        // 广播所以客户端
    public void broadcastMessage(String message) {
        sessionMap.values().forEach(session -> {
            System.out.println("收到ws的消息:" + message);
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error("广播消息发生异常: {}", e.getMessage());
                }
            }
        });
    }
}
